package br.here.data;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.here.exceptions.BDException;
import br.here.utils.HibernateUtil;


public class GenericDAOImpl<T> implements IGenericDAO<T>{

	public void add(T obj) throws BDException {
		
		Session session = HibernateUtil.getCurrentSession();
		Transaction t = session.beginTransaction();
		try{
			session.save(obj);
			t.commit();
		}
		catch(Exception e){
			t.rollback();
			throw new BDException();
		}
	}

	public void remove(T obj) throws BDException {
		
		Session session = HibernateUtil.getCurrentSession();
		Transaction t = session.beginTransaction();
		try{
			session.delete(obj);
			t.commit();
		}
		catch(Exception e){
			t.rollback();
			throw new BDException();
		}
		
		session.close();
	}

	@SuppressWarnings("unchecked")
	public Collection<T> findAll(Class<T> classe) {
		
		Session session = HibernateUtil.getCurrentSession();
		Criteria c = session.createCriteria(classe);
		Collection<T> colecao = c.list();
		session.close();
		return colecao; 
		
	}

	@SuppressWarnings("unchecked")
	public T findByPrimaryKey(int id) {
		
		Session session = HibernateUtil.getCurrentSession();
		
		StringBuilder hql = new StringBuilder();
		hql.append(" from Usuario u where u.id = :id");
		Query q = session.createQuery(hql.toString());
		
		if(id > 0){
			
			q.setInteger("id",id);
			
		}
		session.close();
		return (T) q.uniqueResult();
		
	}

}

